/**
 * jQuery EasyUI 1.4
 *
 * Copyright (c) 2009-2014 www.jeasyui.com. All rights reserved.
 * Licensed under the GPL license: http://www.gnu.org/licenses/gpl.txt To use it
 * on other terms please contact us at info@jeasyui.com
 *
 */
(function ($) {
    var _1 = 0;
    var editIndex = undefined;

    function findIndex(array, o) {
        for (var i = 0, len = array.length; i < len; i++) {
            if (array[i] == o) {
                return i;
            }
        }
        return -1;
    };

    function deleteObject(array, o, id) {
        if (typeof o == "string") {
            for (var i = 0, len = array.length; i < len; i++) {
                if (array[i][o] == id) {
                    array.splice(i, 1);
                    return;
                }
            }
        } else {
            var index = findIndex(array, o);
            if (index != -1) {
                array.splice(index, 1);
            }
        }
    };

    function pushNewObject(array, o, r) {
        for (var i = 0, len = array.length; i < len; i++) {
            if (array[i][o] == r[o]) {
                return;
            }
        }
        array.push(r);
    };

    function createStyleSheet(target) {
        var datagrid = $.data(target, "datagrid");
        var opts = datagrid.options;
        var panel = datagrid.panel;
        var dc = datagrid.dc;
        var ss = null;
        if (opts.sharedStyleSheet) {
            ss = typeof opts.sharedStyleSheet == "boolean" ? "head" : opts.sharedStyleSheet;
        } else {
            ss = panel.closest("div.datagrid-view");
            if (!ss.length) {
                ss = dc.view;
            }
        }
        var cc = $(ss);
        var _e = $.data(cc[0], "ss");
        if (!_e) {
            _e = $.data(cc[0], "ss", {
                cache: {},
                dirty: []
            });
        }
        return {
            add: function (_f) {
                var ss = ["<style type=\"text/css\" easyui=\"true\">"];
                for (var i = 0; i < _f.length; i++) {
                    _e.cache[_f[i][0]] = {
                        width: _f[i][1]
                    };
                }
                var _10 = 0;
                for (var s in _e.cache) {
                    var _11 = _e.cache[s];
                    _11.index = _10++;
                    ss.push(s + "{width:" + _11.width + "}");
                }
                ss.push("</style>");
                $(ss.join("\n")).appendTo(cc);
                cc.children("style[easyui]:not(:last)").remove();
            },
            getRule: function (_12) {
                var _13 = cc.children("style[easyui]:last")[0];
                var _14 = _13.styleSheet ? _13.styleSheet
                    : (_13.sheet || document.styleSheets[document.styleSheets.length - 1]);
                var _15 = _14.cssRules || _14.rules;
                return _15[_12];
            },
            set: function (_16, _17) {
                var _18 = _e.cache[_16];
                if (_18) {
                    _18.width = _17;
                    var _19 = this.getRule(_18.index);
                    if (_19) {
                        _19.style["width"] = _17;
                    }
                }
            },
            remove: function (_1a) {
                var tmp = [];
                for (var s in _e.cache) {
                    if (s.indexOf(_1a) == -1) {
                        tmp.push([s, _e.cache[s].width]);
                    }
                }
                _e.cache = {};
                this.add(tmp);
            },
            dirty: function (_1b) {
                if (_1b) {
                    _e.dirty.push(_1b);
                }
            },
            clean: function () {
                for (var i = 0; i < _e.dirty.length; i++) {
                    this.remove(_e.dirty[i]);
                }
                _e.dirty = [];
            }
        };
    };

    function endEditing(target) {
        if (editIndex == undefined) {
            return true;
        }
        if (validateRow(target, editIndex)) {
            endEdit(target, editIndex);
            editIndex = undefined;
            return true;
        } else {
            return false;
        }
    }

    function setCellEditing(target, index, field) {
        if (endEditing(target)) {
            selectRow(target, index);
            editCell(target, {index: index, field: field});
            editIndex = index;
        }
    }

    function resizeGrid(target, options) {
        var datagrid = $.data(target, "datagrid");
        var opts = datagrid.options;
        var panel = datagrid.panel;
        if (options) {
            $.extend(opts, options);
        }
        if (opts.fit == true) {
            //表格可以暂时不需要。2015-5-20
            var p = panel.panel("panel").parent().parent();
            //var p = panel.panel("panel").parent();
            opts.width = p.width();
            opts.height = p.height();
        }
        panel.panel("resize", opts);
    };

    function setSize(target) {
        var datagrid = $.data(target, "datagrid");
        var opts = datagrid.options;
        var dc = datagrid.dc;
        var panel = datagrid.panel;
        var pwidth = panel.width();
        var pheight = panel.height();
        var view = dc.view;
        var view1 = dc.view1;
        var view2 = dc.view2;
        var header1 = view1.children("div.datagrid-header");
        var header2 = view2.children("div.datagrid-header");
        var table1 = header1.find("table");
        var table2 = header2.find("table");
        view.width(pwidth);
        var inner = header1.children("div.datagrid-header-inner").show();
        view1.width(inner.find("table").width());
        if (!opts.showHeader) {
            inner.hide();
        }
        view2.width(pwidth - view1._outerWidth());
        view1.children("div.datagrid-header,div.datagrid-body,div.datagrid-footer").width(view1.width());
        view2.children("div.datagrid-header,div.datagrid-body,div.datagrid-footer").width(view2.width());
        var hh;
        header1.add(header2).css("height", "");
        table1.add(table2).css("height", "");
        hh = Math.max(table1.height(), table2.height());
        table1.add(table2).height(hh);
        header1.add(header2)._outerHeight(hh);
        dc.body1.add(dc.body2).children("table.datagrid-btable-frozen").css({
            position: "absolute",
            top: dc.header2._outerHeight()
        });
        var marginTop = dc.body2.children("table.datagrid-btable-frozen")._outerHeight();
        var headerheight = marginTop + view2.children("div.datagrid-header")._outerHeight()
            + view2.children("div.datagrid-footer")._outerHeight()
            + panel.children("div.datagrid-toolbar")._outerHeight();
        panel.children("div.datagrid-pager").each(function () {
            headerheight += $(this)._outerHeight();
        });
        var panelheight = panel.outerHeight() - panel.height();
        var panelminHeight = panel._size("minHeight") || "";
        var panelmaxHeight = panel._size("maxHeight") || "";
        view1.add(view2).children("div.datagrid-body").css({
            marginTop: marginTop,
            height: (isNaN(parseInt(opts.height)) ? "" : (pheight - headerheight)),
            minHeight: (panelminHeight ? panelminHeight - panelheight - headerheight : ""),
            maxHeight: (panelmaxHeight ? panelmaxHeight - panelheight - headerheight : "")
        });
        view.height(view2.height());
    };

    function fixRowHeight(target, id, _bool) {
        var opts = $.data(target, "datagrid").options;
        var dc = $.data(target, "datagrid").dc;
        if (!dc.body1.is(":empty") && (!opts.nowrap || opts.autoRowHeight || _bool)) {
            if (id != undefined) {
                var tr1 = opts.finder.getTr(target, id, "body", 1);
                var tr2 = opts.finder.getTr(target, id, "body", 2);
                _setMaxHeight(tr1, tr2);
            } else {
                var tr1 = opts.finder.getTr(target, 0, "allbody", 1);
                var tr2 = opts.finder.getTr(target, 0, "allbody", 2);
                _setMaxHeight(tr1, tr2);
                if (opts.showFooter) {
                    var tr1 = opts.finder.getTr(target, 0, "allfooter", 1);
                    var tr2 = opts.finder.getTr(target, 0, "allfooter", 2);
                    _setMaxHeight(tr1, tr2);
                }
            }
        }
        setSize(target);
        if (opts.height == "auto") {
            var parent = dc.body1.parent();
            var body2 = dc.body2;
            var hw = _firameWidthHeight(body2);
            var height = hw.height;
            if (hw.width > body2.width()) {
                height += 18;
            }
            height -= parseInt(body2.css("marginTop")) || 0;
            parent.height(height);
            body2.height(height);
            dc.view.height(dc.view2.height());
        }
        dc.body2.triggerHandler("scroll");

        function _setMaxHeight(_tr1, _tr2) {
            for (var i = 0; i < _tr2.length; i++) {
                var tr1 = $(_tr1[i]);
                var tr2 = $(_tr2[i]);
                tr1.css("height", "");
                tr2.css("height", "");
                var maxHeight = Math.max(tr1.height(), tr2.height());
                tr1.css("height", maxHeight);
                tr2.css("height", maxHeight);
            }
        };

        function _firameWidthHeight(body) {
            var outerWidth = 0;
            var outerHeigh = 0;
            $(body).children().each(function () {
                var c = $(this);
                if (c.is(":visible")) {
                    outerHeigh += c._outerHeight();
                    if (outerWidth < c._outerWidth()) {
                        outerWidth = c._outerWidth();
                    }
                }
            });
            return {
                width: outerWidth,
                height: outerHeigh
            };
        };
    };

    function freezeRow(target, id) {
        var datagrid = $.data(target, "datagrid");
        var opts = datagrid.options;
        var dc = datagrid.dc;
        if (!dc.body2.children("table.datagrid-btable-frozen").length) {
            dc.body1.add(dc.body2).prepend("<table class=\"datagrid-btable datagrid-btable-frozen\" cellspacing=\"0\" cellpadding=\"0\"></table>");
        }
        _btableFrozen(true);
        _btableFrozen(false);
        setSize(target);

        function _btableFrozen(viewType) {
            var _btr = viewType ? 1 : 2;
            var tr = opts.finder.getTr(target, id, "body", _btr);
            (viewType ? dc.body1 : dc.body2).children("table.datagrid-btable-frozen").append(tr);
        }
        ;
    };

    function buildDatagrid(target, rownumbers) {
        function _createDatagridColumns() {
            var frozenColumns = [];
            var columns = [];
            $(target).children("thead").each(function () {
                var opt = $.parser.parseOptions(this, [{
                    frozen: "boolean"
                }]);
                $(this).find("tr").each(function () {
                    var colarray = [];
                    $(this).find("th").each(function () {
                        var th = $(this);
                        var col = $.extend({}, $.parser.parseOptions(this,
                            ["field",
                                "align",
                                "halign",
                                "order",
                                "width", {
                                sortable: "boolean",
                                checkbox: "boolean",
                                resizable: "boolean",
                                fixed: "boolean"
                            }, {
                                rowspan: "number",
                                colspan: "number"
                            }]), {
                            title: (th.html() || undefined),
                            hidden: (th.attr("hidden") ? true : undefined),
                            formatter: (th.attr("formatter") ? eval(th.attr("formatter")) : undefined),
                            styler: (th.attr("styler") ? eval(th.attr("styler")) : undefined),
                            sorter: (th.attr("sorter") ? eval(th.attr("sorter")) : undefined)
                        });
                        if (col.width && String(col.width).indexOf("%") == -1) {
                            col.width = parseInt(col.width);
                        }
                        if (th.attr("editor")) {
                            var s = $.trim(th.attr("editor"));
                            if (s.substr(0, 1) == "{") {
                                col.editor = eval("(" + s + ")");
                            } else {
                                col.editor = s;
                            }
                        }
                        colarray.push(col);
                    });
                    opt.frozen ? frozenColumns.push(colarray) : columns.push(colarray);
                });
            });
            return [frozenColumns, columns];
        };
        var datagridWrap = $("<div class=\"datagrid-wrap\">"
            + "<div class=\"datagrid-view\">"
            + "<div class=\"datagrid-view1\">"
            + "<div class=\"datagrid-header\">"
            + "<div class=\"datagrid-header-inner\"></div>"
            + "</div>" + "<div class=\"datagrid-body\">"
            + "<div class=\"datagrid-body-inner\"></div>"
            + "</div>" + "<div class=\"datagrid-footer\">"
            + "<div class=\"datagrid-footer-inner\"></div>"
            + "</div>" + "</div>"
            + "<div class=\"datagrid-view2\">"
            + "<div class=\"datagrid-header\">"
            + "<div class=\"datagrid-header-inner\"></div>"
            + "</div>" + "<div class=\"datagrid-body\"></div>"
            + "<div class=\"datagrid-footer\">"
            + "<div class=\"datagrid-footer-inner\"></div>"
            + "</div>" + "</div>" + "</div>" + "</div>").insertAfter(target);
        datagridWrap.panel({
            doSize: false,
            cls: "datagrid"
        });
        //表格可以暂时不需要。2015-5-20
        var tableWarp = $('<div class="datagrid-top-wrap" style="position: relative;"></div>');
        tableWarp.data("datagridWrap", datagridWrap);
        datagridWrap.parent().wrap(tableWarp);
        $(target).hide().appendTo(datagridWrap.children("div.datagrid-view"));
        var cc = _createDatagridColumns();
        var view = datagridWrap.children("div.datagrid-view");
        var view1 = view.children("div.datagrid-view1");
        var view2 = view.children("div.datagrid-view2");
        return {
            panel: datagridWrap,
            frozenColumns: cc[0],
            columns: cc[1],
            dc: {
                view: view,
                view1: view1,
                view2: view2,
                header1: view1.children("div.datagrid-header").children("div.datagrid-header-inner"),
                header2: view2.children("div.datagrid-header").children("div.datagrid-header-inner"),
                body1: view1.children("div.datagrid-body").children("div.datagrid-body-inner"),
                body2: view2.children("div.datagrid-body"),
                footer1: view1.children("div.datagrid-footer").children("div.datagrid-footer-inner"),
                footer2: view2.children("div.datagrid-footer").children("div.datagrid-footer-inner")
            }
        };
    };

    function createDatagrid(target) {
        var datagrid = $.data(target, "datagrid");
        var opts = datagrid.options;
        var dc = datagrid.dc;
        var panel = datagrid.panel;
        datagrid.ss = $(target).datagrid("createStyleSheet");
        panel.panel($.extend({}, opts, {
            id: null,
            doSize: false,
            onResize: function (width, height) {
                setTimeout(function () {
                    if ($.data(target, "datagrid")) {
                        setSize(target);
                        fitColumns(target);
                        opts.onResize.call(panel, width, height);
                    }
                }, 0);
            },
            onExpand: function () {
                fixRowHeight(target);
                opts.onExpand.call(panel);
            }
        }));
        datagrid.rowIdPrefix = "datagrid-row-r" + (++_1);
        datagrid.cellClassPrefix = "datagrid-cell-c" + _1;
        _createColumns(dc.header1, opts.frozenColumns, true);
        _createColumns(dc.header2, opts.columns, false);
        _setDatagridPrefix();
        dc.header1.add(dc.header2).css("display", opts.showHeader ? "block" : "none");
        dc.footer1.add(dc.footer2).css("display", opts.showFooter ? "block" : "none");
        if (opts.toolbar) {
            if ($.isArray(opts.toolbar)) {
                $("div.datagrid-toolbar", panel).remove();
                var tb = $("<div class=\"datagrid-toolbar\"><table cellspacing=\"0\" cellpadding=\"0\"><tr></tr></table></div>").prependTo(panel);
                var tr = tb.find("tr");
                for (var i = 0; i < opts.toolbar.length; i++) {
                    var btn = opts.toolbar[i];
                    if (btn == "-") {
                        $("<td><div class=\"datagrid-btn-separator\"></div></td>").appendTo(tr);
                    } else {
                        var td = $("<td></td>").appendTo(tr);
                        var _a = $("<a href=\"javascript:void(0)\"></a>").appendTo(td);
                        _a[0].onclick = eval(btn.handler || function () {
                        });
                        _a.linkbutton($.extend({}, btn, {
                            plain: true
                        }));
                    }
                }
            } else {
                $(opts.toolbar).addClass("datagrid-toolbar").prependTo(panel);
                $(opts.toolbar).show();
            }
        } else {
            $("div.datagrid-toolbar", panel).remove();
        }
        $("div.datagrid-pager", panel).remove();
        if (opts.pagination) {
            var pager = $("<div class=\"datagrid-pager pager-default\"></div>");
            if (opts.pagePosition == "bottom") {
                pager.appendTo(panel);
            } else {
                if (opts.pagePosition == "top") {
                    pager.addClass("datagrid-pager-top").prependTo(panel);
                } else {
                    var pagertop = $("<div class=\"datagrid-pager datagrid-pager-top\"></div>").prependTo(panel);
                    pager.appendTo(panel);
                    pager = pager.add(pagertop);
                }
            }
            pager.pagination({
                total: (opts.pageNumber * opts.pageSize),
                pageNumber: opts.pageNumber,
                pageSize: opts.pageSize,
                pageList: opts.pageList,
                buttons: opts.pageButtons,
                buttonPosition: opts.buttonPosition,
                showPageList: opts.showPageList,
                showPageStyle: opts.showPageStyle,
                showMsg: opts.showMsg,
                onSelectPage: function (pageNumber, pageSize) {
                    opts.pageNumber = pageNumber;
                    opts.pageSize = pageSize;
//					pager.pagination("refresh", {
//						pageNumber : pageNumber,
//						pageSize : pageSize
//					});
                    request(target);
                }
            });
            opts.pageSize = pager.pagination("options").pageSize;
        }

        function _createColumns(headerView, columns, _bool) {
            if (!columns) {
                return;
            }
            $(headerView).show();
            $(headerView).empty();
            var sortName = [];
            var sortOrder = [];
            if (opts.sortName) {
                sortName = opts.sortName.split(",");
                sortOrder = opts.sortOrder.split(",");
            }
            var t = $("<table class=\"datagrid-htable\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tbody></tbody></table>").appendTo(headerView);
            for (var i = 0; i < columns.length; i++) {
                var tr = $("<tr class=\"datagrid-header-row\"></tr>").appendTo($("tbody", t));
                var column = columns[i];
                for (var j = 0; j < column.length; j++) {
                    var col = column[j];
                    var rowspanHtml = "";
                    if (col.rowspan) {
                        rowspanHtml += "rowspan=\"" + col.rowspan + "\" ";
                    }
                    if (col.colspan) {
                        rowspanHtml += "colspan=\"" + col.colspan + "\" ";
                    }
                    var td = $("<td " + rowspanHtml + "></td>").appendTo(tr);
                    if (col.checkbox) {
                        td.attr("field", col.field);
                        $("<div class=\"datagrid-header-check\"></div>").html("<input type=\"checkbox\"/>").appendTo(td);
                    } else {
                        if (col.field) {
                            td.attr("field", col.field);
                            td.append("<div class=\"datagrid-cell\"><span></span><span class=\"datagrid-sort-icon\"></span></div>");
                            //
                            if (col.titleFn) {
                                $("span", td).html(col.titleFn(col.title, col));
                            } else {
                                $("span", td).html(col.title);
                            }
                            $("span.datagrid-sort-icon", td).html("&nbsp;");
                            var cell = td.find("div.datagrid-cell");
                            var pos = findIndex(sortName, col.field);
                            if (pos >= 0) {
                                cell.addClass("datagrid-sort-" + sortOrder[pos]);
                            }
                            if (col.resizable == false) {
                                cell.attr("resizable", "false");
                            }
                            if (col.width) {
                                var colWidth = $.parser.parseValue("width", col.width, dc.view, opts.scrollbarSize);
                                cell._outerWidth(colWidth - 1);
                                col.boxWidth = parseInt(cell[0].style.width);
                                col.deltaWidth = colWidth - col.boxWidth;
                            } else {
                                col.auto = true;
                            }
                            cell.css("text-align", (col.halign || col.align || ""));
                            col.cellClass = datagrid.cellClassPrefix + "-" + col.field.replace(/[\.|\s]/g, "-");
                            cell.addClass(col.cellClass).css("width", "");
                        } else {
                            $("<div class=\"datagrid-cell-group\"></div>").html(col.title).appendTo(td);
                        }
                    }
                    if (col.hidden) {
                        td.hide();
                    }
                }
            }
            if (_bool && opts.rownumbers) {
                var _td = $("<td rowspan=\"" + opts.frozenColumns.length + "\"><div class=\"datagrid-header-rownumber\"></div></td>");
                if ($("tr", t).length == 0) {
                    _td.wrap("<tr class=\"datagrid-header-row\"></tr>").parent().appendTo($("tbody", t));
                } else {
                    _td.prependTo($("tr:first", t));
                }
            }
        };

        function _setDatagridPrefix() {
            var colArray = [];
            var _fields = getColumnFields(target, true).concat(getColumnFields(target));
            for (var i = 0; i < _fields.length; i++) {
                var col = getColumnOption(target, _fields[i]);
                if (col && !col.checkbox) {
                    colArray.push(["." + col.cellClass, col.boxWidth ? col.boxWidth + "px" : "auto"]);
                }
            }
            datagrid.ss.add(colArray);
            datagrid.ss.dirty(datagrid.cellSelectorPrefix);
            datagrid.cellSelectorPrefix = "." + datagrid.cellClassPrefix;
        };
    };

    function bindEvent(target) {
        var datagrid = $.data(target, "datagrid");
        var panel = datagrid.panel;
        var opts = datagrid.options;
        var dc = datagrid.dc;
        var headers = dc.header1.add(dc.header2);
        headers.find("input[type=checkbox]").unbind(".datagrid").bind("click.datagrid", function (e) {
            if (opts.singleSelect && opts.selectOnCheck) {
                return false;
            }
            if ($(this).is(":checked")) {
                checkAll(target);
            } else {
                uncheckAll(target);
            }
            e.stopPropagation();
        });
        var datagridCells = headers.find("div.datagrid-cell");
        datagridCells.closest("td").unbind(".datagrid").bind("mouseenter.datagrid", function () {
            if (datagrid.resizing) {
                return;
            }
            $(this).addClass("datagrid-header-over");
        }).bind("mouseleave.datagrid", function () {
            $(this).removeClass("datagrid-header-over");
        }).bind("contextmenu.datagrid", function (e) {
            var fieldLabel = $(this).attr("field");
            opts.onHeaderContextMenu.call(target, e, fieldLabel);
        });
        datagridCells.unbind(".datagrid").bind("click.datagrid", function (e) {
            var p1 = $(this).offset().left + 5;
            var p2 = $(this).offset().left + $(this)._outerWidth() - 5;
            if (e.pageX < p2 && e.pageX > p1) {
                sortGrid(target, $(this).parent().attr("field"));
            }
        }).bind("dblclick.datagrid", function (e) {
            var p1 = $(this).offset().left + 5;
            var p2 = $(this).offset().left + $(this)._outerWidth() - 5;
            var _7d = opts.resizeHandle == "right" ? (e.pageX > p2) : (opts.resizeHandle == "left" ? (e.pageX < p1) : (e.pageX < p1 || e.pageX > p2));
            if (_7d) {
                var pfieldLebel = $(this).parent().attr("field");
                var col = getColumnOption(target, pfieldLebel);
                if (col.resizable == false) {
                    return;
                }
                $(target).datagrid("autoSizeColumn", pfieldLebel);
                col.auto = false;
            }
        });
        var ew = opts.resizeHandle == "right" ? "e" : (opts.resizeHandle == "left" ? "w" : "e,w");
        datagridCells.each(function () {
            $(this).resizable({
                handles: ew,
                disabled: ($(this).attr("resizable") ? $(this).attr("resizable") == "false" : false),
                minWidth: 25,
                onStartResize: function (e) {
                    datagrid.resizing = true;
                    headers.css("cursor", $("body").css("cursor"));
                    if (!datagrid.proxy) {
                        datagrid.proxy = $("<div class=\"datagrid-resize-proxy\"></div>").appendTo(dc.view);
                    }
                    datagrid.proxy.css({
                        left: e.pageX - $(panel).offset().left - 1,
                        display: "none"
                    });
                    setTimeout(function () {
                        if (datagrid.proxy) {
                            datagrid.proxy.show();
                        }
                    }, 500);
                },
                onResize: function (e) {
                    datagrid.proxy.css({
                        left: e.pageX - $(panel).offset().left - 1,
                        display: "block"
                    });
                    return false;
                },
                onStopResize: function (e) {
                    headers.css("cursor", "");
                    $(this).css("height", "");
                    var pfieldLebel = $(this).parent().attr("field");
                    var col = getColumnOption(target, pfieldLebel);
                    col.width = $(this)._outerWidth();
                    col.boxWidth = col.width - col.deltaWidth;
                    col.auto = undefined;
                    $(this).css("width", "");
                    fixColumnSize(target, pfieldLebel);
                    datagrid.proxy.remove();
                    datagrid.proxy = null;
                    if ($(this).parents("div:first.datagrid-header").parent().hasClass("datagrid-view1")) {
                        setSize(target);
                    }
                    fitColumns(target);
                    opts.onResizeColumn.call(target, pfieldLebel, col.width);
                    setTimeout(function () {
                        datagrid.resizing = false;
                    }, 0);
                }
            });
        });
        dc.body1.add(dc.body2).unbind().bind("mouseover", function (e) {
            if (datagrid.resizing) {
                return;
            }
            var tr = $(e.target).closest("tr.datagrid-row");
            if (!_trlen(tr)) {
                return;
            }
            var id = _rowIndexId(tr);
            highlightRow(target, id);
            e.stopPropagation();
        }).bind("mouseout", function (e) {
            var tr = $(e.target).closest("tr.datagrid-row");
            if (!_trlen(tr)) {
                return;
            }
            var id = _rowIndexId(tr);
            opts.finder.getTr(target, id).removeClass("datagrid-row-over");
            e.stopPropagation();
        }).bind("click", function (e) {
            var tt = $(e.target);
            var tr = tt.closest("tr.datagrid-row");
            if (!_trlen(tr)) {
                return;
            }
            var id = _rowIndexId(tr);
            if (tt.parent().hasClass("datagrid-cell-check")) {
                if (opts.singleSelect && opts.selectOnCheck) {
                    if (!opts.checkOnSelect) {
                        uncheckAll(target, true);
                    }
                    checkRow(target, id);
                } else {
                    if (tt.is(":checked")) {
                        checkRow(target, id);
                    } else {
                        uncheckRow(target, id);
                    }
                }
            } else {
                var row = opts.finder.getRow(target, id);
                var td = tt.closest("td[field]", tr);
                if (td.length) {
                    var fieldLabel = td.attr("field");
                    if (opts.showEditor) {
                        setCellEditing(target, id, fieldLabel);
                    }
                    opts.onClickCell.call(target, id, fieldLabel, row[fieldLabel]);
                }
                if (opts.singleSelect == true) {
                    selectRow(target, id);
                } else {
                    if (opts.ctrlSelect) {
                        if (e.ctrlKey) {
                            if (tr.hasClass("datagrid-row-selected")) {
                                unselectRow(target, id);
                            } else {
                                selectRow(target, id);
                            }
                        } else {
                            $(target).datagrid("clearSelections");
                            selectRow(target, id);
                        }
                    } else {
                        if (tr.hasClass("datagrid-row-selected")) {
                            unselectRow(target, id);
                        } else {
                            selectRow(target, id);
                        }
                    }
                }
                opts.onClickRow.call(target, id, row);
            }
            e.stopPropagation();
        }).bind("dblclick", function (e) {
            var tt = $(e.target);
            var tr = tt.closest("tr.datagrid-row");
            if (!_trlen(tr)) {
                return;
            }
            var id = _rowIndexId(tr);
            var row = opts.finder.getRow(target, id);
            var td = tt.closest("td[field]", tr);
            if (td.length) {
                var fieldLabel = td.attr("field");
                opts.onDblClickCell.call(target, id, fieldLabel, row[fieldLabel]);
            }
            opts.onDblClickRow.call(target, id, row);
            e.stopPropagation();
        }).bind("contextmenu", function (e) {
            var tr = $(e.target).closest("tr.datagrid-row");
            if (!_trlen(tr)) {
                return;
            }
            var id = _rowIndexId(tr);
            var row = opts.finder.getRow(target, id);
            opts.onRowContextMenu.call(target, e, id, row);
            e.stopPropagation();
        });
        dc.body2.bind("scroll", function () {
            var body = dc.view1.children("div.datagrid-body");
            body.scrollTop($(this).scrollTop());
            var body1 = dc.body1.children(":first");
            var body2 = dc.body2.children(":first");
            if (body1.length && body2.length) {
                var body1Top = body1.offset().top;
                var body2Top = body2.offset().top;
                if (body1Top != body2Top) {
                    body.scrollTop(body.scrollTop() + body1Top - body2Top);
                }
            }
            dc.view2.children("div.datagrid-header,div.datagrid-footer")._scrollLeft($(this)._scrollLeft());
            dc.body2.children("table.datagrid-btable-frozen").css("left", -$(this)._scrollLeft());
        });

        function _rowIndexId(tr) {
            if (tr.attr("datagrid-row-index")) {
                return parseInt(tr.attr("datagrid-row-index"));
            } else {
                return tr.attr("node-id");
            }
        };

        function _trlen(tr) {
            return tr.length && tr.parent().length;
        };
    };

    function sortGrid(target, sortParam) {
        var datagrid = $.data(target, "datagrid");
        var opts = datagrid.options;
        sortParam = sortParam || {};
        var _sortParam = {
            sortName: opts.sortName,
            sortOrder: opts.sortOrder
        };
        if (typeof sortParam == "object") {
            $.extend(_sortParam, sortParam);
        }
        var sortNameArray = [];
        var sortOrderArray = [];
        if (_sortParam.sortName) {
            sortNameArray = _sortParam.sortName.split(",");
            sortOrderArray = _sortParam.sortOrder.split(",");
        }
        if (typeof sortParam == "string") {
            var sortName = sortParam;
            var col = getColumnOption(target, sortName);
            if (!col.sortable || datagrid.resizing) {
                return;
            }
            var colOrder = col.order || "asc";
            var pos = findIndex(sortNameArray, sortName);
            if (pos >= 0) {
                var sortType = sortOrderArray[pos] == "asc" ? "desc" : "asc";
                if (opts.multiSort && sortType == colOrder) {
                    sortNameArray.splice(pos, 1);
                    sortOrderArray.splice(pos, 1);
                } else {
                    sortOrderArray[pos] = sortType;
                }
            } else {
                if (opts.multiSort) {
                    sortNameArray.push(sortName);
                    sortOrderArray.push(colOrder);
                } else {
                    sortNameArray = [sortName];
                    sortOrderArray = [colOrder];
                }
            }
            _sortParam.sortName = sortNameArray.join(",");
            _sortParam.sortOrder = sortOrderArray.join(",");
        }
        if (opts.onBeforeSortColumn.call(target, _sortParam.sortName, _sortParam.sortOrder) == false) {
            return;
        }
        $.extend(opts, _sortParam);
        var dc = datagrid.dc;
        var headers = dc.header1.add(dc.header2);
        headers.find("div.datagrid-cell").removeClass("datagrid-sort-asc datagrid-sort-desc");
        for (var i = 0; i < sortNameArray.length; i++) {
            var col = getColumnOption(target, sortNameArray[i]);
            headers.find("div." + col.cellClass).addClass("datagrid-sort-" + sortOrderArray[i]);
        }
        if (opts.remoteSort) {
            request(target);
        } else {
            renderDatagridLoadData(target, $(target).datagrid("getData"));
        }
        opts.onSortColumn.call(target, opts.sortName, opts.sortOrder);
    };

    function fitColumns(target) {
        var datagrid = $.data(target, "datagrid");
        var opts = datagrid.options;
        var dc = datagrid.dc;
        var headers = dc.view2.children("div.datagrid-header");
        dc.body2.css("overflow-x", "");
        _setFixColumnSize();
        _a0();
        if (headers.width() >= headers.find("table").width()) {
            dc.body2.css("overflow-x", "hidden");
        }

        function _a0() {
            if (!opts.fitColumns) {
                return;
            }
            if (!datagrid.leftWidth) {
                datagrid.leftWidth = 0;
            }
            var _a1 = 0;
            var cc = [];
            var _a2 = getColumnFields(target, false);
            for (var i = 0; i < _a2.length; i++) {
                var col = getColumnOption(target, _a2[i]);
                if (_a3(col)) {
                    _a1 += col.width;
                    cc.push({
                        field: col.field,
                        col: col,
                        addingWidth: 0
                    });
                }
            }
            if (!_a1) {
                return;
            }
            cc[cc.length - 1].addingWidth -= datagrid.leftWidth;
            var _a4 = headers.children("div.datagrid-header-inner").show();
            var _a5 = headers.width() - headers.find("table").width() - opts.scrollbarSize + datagrid.leftWidth;
            var _a6 = _a5 / _a1;
            if (!opts.showHeader) {
                _a4.hide();
            }
            for (var i = 0; i < cc.length; i++) {
                var c = cc[i];
                var _a7 = parseInt(c.col.width * _a6);
                c.addingWidth += _a7;
                _a5 -= _a7;
            }
            if (_a5 > 0) {
                _a5 = 0 - _a5;
            }
            cc[cc.length - 1].addingWidth += _a5;
            for (var i = 0; i < cc.length; i++) {
                var c = cc[i];
                if (c.col.boxWidth + c.addingWidth > 0) {
                    c.col.boxWidth += c.addingWidth;
                    c.col.width += c.addingWidth;
                }
            }
            datagrid.leftWidth = _a5;
            fixColumnSize(target);
        };

        function _setFixColumnSize() {
            var _bool = false;
            var fields = getColumnFields(target, true).concat(getColumnFields(target, false));
            $.map(fields, function (_aa) {
                var col = getColumnOption(target, _aa);
                if (String(col.width || "").indexOf("%") >= 0) {
                    var colWidth = $.parser.parseValue("width", col.width, dc.view, opts.scrollbarSize) - col.deltaWidth;
                    if (colWidth > 0) {
                        col.boxWidth = colWidth;
                        _bool = true;
                    }
                }
            });
            if (_bool) {
                fixColumnSize(target);
            }
        };

        function _a3(col) {
            if (String(col.width || "").indexOf("%") >= 0) {
                return false;
            }
            if (!col.hidden && !col.checkbox && !col.auto && !col.fixed) {
                return true;
            }
        };
    };

    function autoSizeColumn(target, fieldLabel) {
        var datagrid = $.data(target, "datagrid");
        var opts = datagrid.options;
        var dc = datagrid.dc;
        var tmp = $("<div class=\"datagrid-cell\" style=\"position:absolute;left:-9999px\"></div>").appendTo("body");
        if (fieldLabel) {
            _resizeGrid(fieldLabel);
            if (opts.fitColumns) {
                setSize(target);
                fitColumns(target);
            }
        } else {
            var _b = false;
            var fields = getColumnFields(target, true).concat(getColumnFields(target, false));
            for (var i = 0; i < fields.length; i++) {
                var field = fields[i];
                var col = getColumnOption(target, field);
                if (col.auto) {
                    _resizeGrid(field);
                    _b = true;
                }
            }
            if (_b && opts.fitColumns) {
                setSize(target);
                fitColumns(target);
            }
        }
        tmp.remove();

        function _resizeGrid(_fieldLabel) {
            var datagridCell = dc.view.find("div.datagrid-header td[field=\"" + _fieldLabel + "\"] div.datagrid-cell");
            datagridCell.css("width", "");
            var col = $(target).datagrid("getColumnOption", _fieldLabel);
            col.width = undefined;
            col.boxWidth = undefined;
            col.auto = true;
            $(target).datagrid("fixColumnSize", _fieldLabel);
            var _b5 = Math.max(_getCellWidth("header"), _getCellWidth("allbody"), _getCellWidth("allfooter")) + 1;
            datagridCell._outerWidth(_b5 - 1);
            col.width = _b5;
            col.boxWidth = parseInt(datagridCell[0].style.width);
            col.deltaWidth = _b5 - col.boxWidth;
            datagridCell.css("width", "");
            $(target).datagrid("fixColumnSize", _fieldLabel);
            opts.onResizeColumn.call(target, _fieldLabel, col.width);

            function _getCellWidth(viewType) {
                var cellWidth = 0;
                if (viewType == "header") {
                    cellWidth = _b9(datagridCell);
                } else {
                    opts.finder.getTr(target, 0, viewType).find("td[field=\"" + _fieldLabel + "\"] div.datagrid-cell").each(function () {
                        var w = _b9($(this));
                        if (cellWidth < w) {
                            cellWidth = w;
                        }
                    });
                }
                return cellWidth;

                function _b9(_cell) {
                    return _cell.is(":visible") ? _cell._outerWidth() : tmp.html(_cell.html())._outerWidth();
                };
            };
        };
    };

    function fixColumnSize(target, index) {
        var datagrid = $.data(target, "datagrid");
        var dc = datagrid.dc;
        var ftable = dc.view.find("table.datagrid-btable,table.datagrid-ftable");
        ftable.css("table-layout", "fixed");
        if (index) {
            fix(index);
        } else {
            var ff = getColumnFields(target, true).concat(getColumnFields(target, false));
            for (var i = 0; i < ff.length; i++) {
                fix(ff[i]);
            }
        }
        ftable.css("table-layout", "auto");
        setMergedWidth(target);
        fixRowHeight(target);
        setEditableWidth(target);

        function fix(indx) {
            var col = getColumnOption(target, indx);
            if (col.cellClass) {
                datagrid.ss.set("." + col.cellClass, col.boxWidth ? col.boxWidth + "px" : "auto");
            }
        };
    };

    function setMergedWidth(target) {
        var dc = $.data(target, "datagrid").dc;
        dc.view.find("td.datagrid-td-merged").each(function () {
            var td = $(this);
            var colspan = td.attr("colspan") || 1;
            var col = getColumnOption(target, td.attr("field"));
            var boxWidth = col.boxWidth + col.deltaWidth - 1;
            for (var i = 1; i < colspan; i++) {
                td = td.next();
                col = getColumnOption(target, td.attr("field"));
                boxWidth += col.boxWidth + col.deltaWidth;
            }
            $(this).children("div.datagrid-cell")._outerWidth(boxWidth);
        });
    };

    function setEditableWidth(target) {
        var dc = $.data(target, "datagrid").dc;
        dc.view.find("div.datagrid-editable").each(function () {
            var editable = $(this);
            var pfield = editable.parent().attr("field");
            var col = $(target).datagrid("getColumnOption", pfield);
            editable._outerWidth(col.boxWidth + col.deltaWidth - 1);
            var ed = $.data(this, "datagrid.editor");
            if (ed.actions.resize) {
                ed.actions.resize(ed.target, editable.width());
            }
        });
    };

    function getColumnOption(target, _cb) {
        function _cc(_cd) {
            if (_cd) {
                for (var i = 0; i < _cd.length; i++) {
                    var cc = _cd[i];
                    for (var j = 0; j < cc.length; j++) {
                        var c = cc[j];
                        if (c.field == _cb) {
                            return c;
                        }
                    }
                }
            }
            return null;
        };
        var opts = $.data(target, "datagrid").options;
        var col = _cc(opts.columns);
        if (!col) {
            col = _cc(opts.frozenColumns);
        }
        return col;
    };

    function getColumnFields(target, _bool) {
        var opts = $.data(target, "datagrid").options;
        var array = (_bool == true) ? (opts.frozenColumns || [[]]) : opts.columns;
        if (array.length == 0) {
            return [];
        }
        var columns = [];
        var _index = _mapColspanIndex();
        for (var i = 0; i < array.length; i++) {
            columns[i] = new Array(_index);
        }
        for (var _n = 0; _n < array.length; _n++) {
            $.map(array[_n], function (col) {
                var _inx = _isUndefined(columns[_n]);
                if (_inx >= 0) {
                    var _d8 = col.field || "";
                    for (var c = 0; c < (col.colspan || 1); c++) {
                        for (var r = 0; r < (col.rowspan || 1); r++) {
                            columns[_n + r][_inx] = _d8;
                        }
                        _inx++;
                    }
                }
            });
        }
        return columns[columns.length - 1];

        function _mapColspanIndex() {
            var index = 0;
            $.map(array[0], function (col) {
                index += col.colspan || 1;
            });
            return index;
        };

        function _isUndefined(a) {
            for (var i = 0; i < a.length; i++) {
                if (a[i] == undefined) {
                    return i;
                }
            }
            return -1;
        };
    };

    function renderDatagridLoadData(target, data) {
        var datagrid = $.data(target, "datagrid");
        var opts = datagrid.options;
        var dc = datagrid.dc;
        data = opts.loadFilter.call(target, data);
        data.total = parseInt(data.total);
        datagrid.data = data;
        if (data.footer) {
            datagrid.footer = data.footer;
        }
        if (data.total <= 0 && opts.emptyMessage) {
            dc.view1.children("div.datagrid-header").hide();
            dc.view2.children("div.datagrid-header").hide();
        } else {
            dc.view1.children("div.datagrid-header").show();
            dc.view2.children("div.datagrid-header").show();
        }
        if (opts.toolbar && $(opts.toolbar).length) {
            if (data.total <= 0 && opts.emptyMessage) {
                $(opts.toolbar).hide();
            } else {
                $(opts.toolbar).show();
            }
        }

        if (!opts.remoteSort && opts.sortName) {
            var sortNameArray = opts.sortName.split(",");
            var sortOrderArray = opts.sortOrder.split(",");
            data.rows.sort(function (r1, r2) {
                var r = 0;
                for (var i = 0; i < sortNameArray.length; i++) {
                    var sn = sortNameArray[i];
                    var so = sortOrderArray[i];
                    var col = getColumnOption(target, sn);
                    var _e0 = col.sorter || function (a, b) {
                        return a == b ? 0 : (a > b ? 1 : -1);
                    };
                    r = _e0(r1[sn], r2[sn]) * (so == "asc" ? 1 : -1);
                    if (r != 0) {
                        return r;
                    }
                }
                return r;
            });
        }
        if (opts.view.onBeforeRender) {
            opts.view.onBeforeRender.call(opts.view, target, data.rows);
        }
        opts.view.render.call(opts.view, target, dc.body2, false);
        opts.view.render.call(opts.view, target, dc.body1, true);
        if (opts.showFooter) {
            opts.view.renderFooter.call(opts.view, target, dc.footer2, false);
            opts.view.renderFooter.call(opts.view, target, dc.footer1, true);
        }
        if (opts.view.onAfterRender) {
            opts.view.onAfterRender.call(opts.view, target);
        }
        datagrid.ss.clean();
        var pager = $(target).datagrid("getPager");
        if (data.total <= 0 && opts.emptyMessage) {
            pager.hide();
        } else {
            pager.show();
            if (pager.length) {
                var pagerOpts = pager.pagination("options");
                if (pagerOpts.total != data.total) {
                    pager.pagination("refresh", {
                        total: data.total
                    });
                    if (data.total > 0 && opts.pageNumber != pagerOpts.pageNumber) {
                        opts.pageNumber = pagerOpts.pageNumber;
                        request(target);
                    }
                }
            }
        }


        fixRowHeight(target);
        dc.body2.triggerHandler("scroll");
        setSelectionState(target);
        autoSizeColumn(target);
        opts.onLoadSuccess.call(target, data);
        resizeGrid(target);

    };

    function setSelectionState(target) {
        var datagrid = $.data(target, "datagrid");
        var opts = datagrid.options;
        var dc = datagrid.dc;
        dc.header1.add(dc.header2).find("input[type=checkbox]")._propAttr("checked", false);
        if (opts.idField) {
            var isTree = $.data(target, "treegrid") ? true : false;
            var onSelect = opts.onSelect;
            var onCheck = opts.onCheck;
            opts.onSelect = opts.onCheck = function () {
            };
            var rows = opts.finder.getRows(target);
            for (var i = 0; i < rows.length; i++) {
                var row = rows[i];
                var idField = isTree ? row[opts.idField] : i;
                if (_compareIdField(datagrid.selectedRows, row)) {
                    selectRow(target, idField, true);
                }
                if (_compareIdField(datagrid.checkedRows, row)) {
                    checkRow(target, idField, true);
                }
            }
            opts.onSelect = onSelect;
            opts.onCheck = onCheck;
        }

        //2016-1-29增加，当前为checkd时，保存到选中去
        function _compareIdField(a, r) {
            for (var i = 0; i < a.length; i++) {
                if (a[i][opts.idField] == r[opts.idField]) {
                    a[i] = r;
                    return true;
                }
            }
            if (r["checked"] == true) {
                return true;
            } else {
                return false;
            }
        };
    };

    function getRowIndex(target, row) {
        var datagrid = $.data(target, "datagrid");
        var opts = datagrid.options;
        var rows = datagrid.data.rows;
        if (typeof row == "object") {
            return findIndex(rows, row);
        } else {
            for (var i = 0; i < rows.length; i++) {
                if (rows[i][opts.idField] == row) {
                    return i;
                }
            }
            return -1;
        }
    };

    function getSelectedRow(target) {
        var datagrid = $.data(target, "datagrid");
        var opts = datagrid.options;
        if (opts.idField) {
            return datagrid.selectedRows;
        } else {
            var selectedArray = [];
            opts.finder.getTr(target, "", "selected", 2).each(function () {
                selectedArray.push(opts.finder.getRow(target, $(this)));
            });
            return selectedArray;
        }
    };

    function getChecked(target) {
        var datagrid = $.data(target, "datagrid");
        var opts = datagrid.options;
        if (opts.idField) {
            return datagrid.checkedRows;
        } else {
            var checkedArray = [];
            opts.finder.getTr(target, "", "checked", 2).each(function () {
                checkedArray.push(opts.finder.getRow(target, $(this)));
            });
            return checkedArray;
        }
    };

    function scrollTo(target, id) {
        var datagrid = $.data(target, "datagrid");
        var dc = datagrid.dc;
        var opts = datagrid.options;
        var tr = opts.finder.getTr(target, id);
        if (tr.length) {
            if (tr.closest("table").hasClass("datagrid-btable-frozen")) {
                return;
            }
            var headerOuterHeight = dc.view2.children("div.datagrid-header")._outerHeight();
            var body2 = dc.body2;
            var body2OuterHeight = body2.outerHeight(true) - body2.outerHeight();
            var top = tr.position().top - headerOuterHeight - body2OuterHeight;
            if (top < 0) {
                body2.scrollTop(body2.scrollTop() + top);
            } else {
                if (top + tr._outerHeight() > body2.height() - 18) {
                    body2.scrollTop(body2.scrollTop() + top + tr._outerHeight() - body2.height() + 18);
                }
            }
        }
    };

    function highlightRow(target, id) {
        var datagrid = $.data(target, "datagrid");
        var opts = datagrid.options;
        opts.finder.getTr(target, datagrid.highlightIndex).removeClass("datagrid-row-over");
        opts.finder.getTr(target, id).addClass("datagrid-row-over");
        datagrid.highlightIndex = id;
    };

    function selectRow(target, id, _bool) {
        var datagrid = $.data(target, "datagrid");
        var opts = datagrid.options;
        var selectedRows = datagrid.selectedRows;
        if (opts.singleSelect) {
            unselectAll(target);
            selectedRows.splice(0, selectedRows.length);
        }
        if (!_bool && opts.checkOnSelect) {
            checkRow(target, id, true);
        }
        var row = opts.finder.getRow(target, id);
        if (opts.idField) {
            pushNewObject(selectedRows, opts.idField, row);
        }
        opts.finder.getTr(target, id).addClass("datagrid-row-selected");
        opts.onSelect.call(target, id, row);
        scrollTo(target, id);
    };

    function unselectRow(target, id, _bool) {
        var datagrid = $.data(target, "datagrid");
        var opts = datagrid.options;
        var selectedRows = $.data(target, "datagrid").selectedRows;
        if (!_bool && opts.checkOnSelect) {
            uncheckRow(target, id, true);
        }
        opts.finder.getTr(target, id).removeClass("datagrid-row-selected");
        var row = opts.finder.getRow(target, id);
        if (opts.idField) {
            deleteObject(selectedRows, opts.idField, row[opts.idField]);
        }
        opts.onUnselect.call(target, id, row);
    };

    function selectAll(target, _bool) {
        var datagrid = $.data(target, "datagrid");
        var opts = datagrid.options;
        var rows = opts.finder.getRows(target);
        var selectedRows = $.data(target, "datagrid").selectedRows;
        if (!_bool && opts.checkOnSelect) {
            checkAll(target, true);
        }
        opts.finder.getTr(target, "", "allbody").addClass("datagrid-row-selected");
        if (opts.idField) {
            for (var _i = 0; _i < rows.length; _i++) {
                pushNewObject(selectedRows, opts.idField, rows[_i]);
            }
        }
        opts.onSelectAll.call(target, rows);
    };

    function unselectAll(target, _bool) {
        var datagrid = $.data(target, "datagrid");
        var opts = datagrid.options;
        var rows = opts.finder.getRows(target);
        var selectedRows = $.data(target, "datagrid").selectedRows;
        if (!_bool && opts.checkOnSelect) {
            uncheckAll(target, true);
        }
        opts.finder.getTr(target, "", "selected").removeClass("datagrid-row-selected");
        if (opts.idField) {
            for (var _i = 0; _i < rows.length; _i++) {
                deleteObject(selectedRows, opts.idField, rows[_i][opts.idField]);
            }
        }
        opts.onUnselectAll.call(target, rows);
    };


    function checkRow(target, id, _bool) {
        var datagrid = $.data(target, "datagrid");
        var opts = datagrid.options;
        if (!_bool && opts.selectOnCheck) {
            selectRow(target, id, true);
        }
        var tr = opts.finder.getTr(target, id).addClass("datagrid-row-checked");
        var ck = tr.find("div.datagrid-cell-check input[type=checkbox]");
        ck._propAttr("checked", true);
        tr = opts.finder.getTr(target, "", "checked", 2);
        if (tr.length == opts.finder.getRows(target).length) {
            var dc = datagrid.dc;
            var headers = dc.header1.add(dc.header2);
            headers.find("input[type=checkbox]")._propAttr("checked", true);
        }
        var row = opts.finder.getRow(target, id);
        if (opts.idField) {
            pushNewObject(datagrid.checkedRows, opts.idField, row);
        }
        opts.onCheck.call(target, id, row);
    };

    function uncheckRow(target, id, _bool) {
        var datagrid = $.data(target, "datagrid");
        var opts = datagrid.options;
        if (!_bool && opts.selectOnCheck) {
            unselectRow(target, id, true);
        }
        var tr = opts.finder.getTr(target, id).removeClass("datagrid-row-checked");
        var ck = tr.find("div.datagrid-cell-check input[type=checkbox]");
        ck._propAttr("checked", false);
        var dc = datagrid.dc;
        var headers = dc.header1.add(dc.header2);
        headers.find("input[type=checkbox]")._propAttr("checked", false);
        var row = opts.finder.getRow(target, id);
        if (opts.idField) {
            deleteObject(datagrid.checkedRows, opts.idField, row[opts.idField]);
        }
        opts.onUncheck.call(target, id, row);
    };

    function checkAll(target, _bool) {
        var datagrid = $.data(target, "datagrid");
        var opts = datagrid.options;
        var rows = opts.finder.getRows(target);
        if (!_bool && opts.selectOnCheck) {
            selectAll(target, true);
        }
        var dc = datagrid.dc;
        var hck = dc.header1.add(dc.header2).find("input[type=checkbox]");
        var bck = opts.finder.getTr(target, "", "allbody").addClass("datagrid-row-checked").find("div.datagrid-cell-check input[type=checkbox]");
        hck.add(bck)._propAttr("checked", true);
        if (opts.idField) {
            for (var i = 0; i < rows.length; i++) {
                pushNewObject(datagrid.checkedRows, opts.idField, rows[i]);
            }
        }
        opts.onCheckAll.call(target, rows);
    };

    function uncheckAll(target, _bool) {
        var datagrid = $.data(target, "datagrid");
        var opts = datagrid.options;
        var rows = opts.finder.getRows(target);
        if (!_bool && opts.selectOnCheck) {
            unselectAll(target, true);
        }
        var dc = datagrid.dc;
        var hck = dc.header1.add(dc.header2).find("input[type=checkbox]");
        var bck = opts.finder.getTr(target, "", "checked").removeClass("datagrid-row-checked").find("div.datagrid-cell-check input[type=checkbox]");
        hck.add(bck)._propAttr("checked", false);
        if (opts.idField) {
            for (var i = 0; i < rows.length; i++) {
                deleteObject(datagrid.checkedRows, opts.idField, rows[i][opts.idField]);
            }
        }
        opts.onUncheckAll.call(target, rows);
    };


    function beginEdit(target, id) {
        var opts = $.data(target, "datagrid").options;
        var tr = opts.finder.getTr(target, id);
        var row = opts.finder.getRow(target, id);
        if (tr.hasClass("datagrid-row-editing")) {
            return;
        }
        if (opts.onBeforeEdit.call(target, id, row) == false) {
            return;
        }
        tr.addClass("datagrid-row-editing");
        setContextmenu(target, id);
        setEditableWidth(target);
        tr.find("div.datagrid-editable").each(function () {
            var pfield = $(this).parent().attr("field");
            var ed = $.data(this, "datagrid.editor");
            ed.actions.setValue(ed.target, row[pfield]);
        });
        validateRow(target, id);
        opts.onBeginEdit.call(target, id, row);
    };

    function endEdit(target, id, _bool) {
        var datagrid = $.data(target, "datagrid");
        var opts = datagrid.options;
        var updatedRows = datagrid.updatedRows;
        var insertedRows = datagrid.insertedRows;
        var tr = opts.finder.getTr(target, id);
        var row = opts.finder.getRow(target, id);
        if (!tr.hasClass("datagrid-row-editing")) {
            return;
        }
        var fieldObject = {};
        if (!_bool) {
            if (!validateRow(target, id)) {
                return;
            }
            var _b = false;
            tr.find("div.datagrid-editable").each(function () {
                var fieldLabel = $(this).parent().attr("field");
                var ed = $.data(this, "datagrid.editor");
                var fieldValue = ed.actions.getValue(ed.target);
                if (row[fieldLabel] != fieldValue) {
                    row[fieldLabel] = fieldValue;
                    _b = true;
                    fieldObject[fieldLabel] = fieldValue;
                }
            });
            if (_b) {
                if (findIndex(insertedRows, row) == -1) {
                    if (findIndex(updatedRows, row) == -1) {
                        updatedRows.push(row);
                    }
                }
            }
            opts.onEndEdit.call(target, id, row, fieldObject);
        }
        tr.removeClass("datagrid-row-editing");
        setEditableCell(target, id);
        $(target).datagrid("refreshRow", id);
        if (!_bool) {
            opts.onAfterEdit.call(target, id, row, fieldObject);
        } else {
            opts.onCancelEdit.call(target, id, row);
        }
    };

    function editCell(target, param) {
        var fields = getColumnFields(target, true).concat(getColumnFields(target, false));
        for (var i = 0; i < fields.length; i++) {
            var col = getColumnOption(target, fields[i]);
            col.editor1 = col.editor;
            if (fields[i] != param.field) {
                col.editor = null;
            }
        }
        beginEdit(target, param.index);
        for (var n = 0; n < fields.length; n++) {
            var col_ = getColumnOption(target, fields[n]);
            col_.editor = col_.editor1;
        }
    }

    function getEditors(target, id) {
        var opts = $.data(target, "datagrid").options;
        var tr = opts.finder.getTr(target, id);
        var tdArray = [];
        tr.children("td").each(function () {
            var cell = $(this).find("div.datagrid-editable");
            if (cell.length) {
                var ed = $.data(cell[0], "datagrid.editor");
                tdArray.push(ed);
            }
        });
        return tdArray;
    };

    function getEditor(target, _14c) {
        var _14d = getEditors(target, _14c.index != undefined ? _14c.index : _14c.id);
        for (var i = 0; i < _14d.length; i++) {
            if (_14d[i].field == _14c.field) {
                return _14d[i];
            }
        }
        return null;
    };

    function setContextmenu(target, id) {
        var opts = $.data(target, "datagrid").options;
        var tr = opts.finder.getTr(target, id);
        tr.children("td").each(function () {
            var cell = $(this).find("div.datagrid-cell");
            var fieldLabel = $(this).attr("field");
            var col = getColumnOption(target, fieldLabel);
            if (col && col.editor) {
                var editorType, editorOpts = null;
                if (typeof col.editor == "string") {
                    editorType = col.editor;
                } else {
                    editorType = col.editor.type;
                    editorOpts = col.editor.options;
                }
                var editorsTool = opts.editors[editorType];
                if (editorsTool) {
                    var cellHtml = cell.html();
                    var cellWidth = cell._outerWidth();
                    cell.addClass("datagrid-editable");
                    cell._outerWidth(cellWidth);
                    cell.html("<table border=\"0\" cellspacing=\"0\" cellpadding=\"1\"><tr><td></td></tr></table>");
                    cell.children("table").bind("click dblclick contextmenu", function (e) {
                        e.stopPropagation();
                    });
                    $.data(cell[0], "datagrid.editor", {
                        actions: editorsTool,
                        target: editorsTool.init(cell.find("td"), editorOpts),
                        field: fieldLabel,
                        type: editorType,
                        oldHtml: cellHtml
                    });
                }
            }
        });
        fixRowHeight(target, id, true);
    };

    function setEditableCell(target, id) {
        var opts = $.data(target, "datagrid").options;
        var tr = opts.finder.getTr(target, id);
        tr.children("td").each(function () {
            var cell = $(this).find("div.datagrid-editable");
            if (cell.length) {
                var ed = $.data(cell[0], "datagrid.editor");
                if (ed.actions.destroy) {
                    ed.actions.destroy(ed.target);
                }
                cell.html(ed.oldHtml);
                $.removeData(cell[0], "datagrid.editor");
                cell.removeClass("datagrid-editable");
                cell.css("width", "");
            }
        });
    };

    function validateRow(target, _159) {
        var tr = $.data(target, "datagrid").options.finder.getTr(target, _159);
        if (!tr.hasClass("datagrid-row-editing")) {
            return true;
        }
        var vbox = tr.find(".validatebox-text");
        vbox.validatebox("validate");
        vbox.trigger("mouseleave");
        var _15a = tr.find(".validatebox-invalid");
        return _15a.length == 0;
    };

    function getChanges(target, _15d) {
        var insertedRows = $.data(target, "datagrid").insertedRows;
        var deletedRows = $.data(target, "datagrid").deletedRows;
        var updatedRows = $.data(target, "datagrid").updatedRows;
        if (!_15d) {
            var rows = [];
            rows = rows.concat(insertedRows);
            rows = rows.concat(deletedRows);
            rows = rows.concat(updatedRows);
            return rows;
        } else {
            if (_15d == "inserted") {
                return insertedRows;
            } else {
                if (_15d == "deleted") {
                    return deletedRows;
                } else {
                    if (_15d == "updated") {
                        return updatedRows;
                    }
                }
            }
        }
        return [];
    };

    function deleteRow(target, index) {
        var datagrid = $.data(target, "datagrid");
        var opts = datagrid.options;
        var data = datagrid.data;
        var insertedRows = datagrid.insertedRows;
        var deletedRows = datagrid.deletedRows;
        endEdit(target, index, true);
        var row = opts.finder.getRow(target, index);
        if (findIndex(insertedRows, row) >= 0) {
            deleteObject(insertedRows, row);
        } else {
            deletedRows.push(row);
        }
        deleteObject(datagrid.selectedRows, opts.idField, row[opts.idField]);
        deleteObject(datagrid.checkedRows, opts.idField, row[opts.idField]);
        data.total -= 1;
        data.rows.splice(index, 1);
        renderDatagridLoadData(target, data);
    };

    function insertRow(target, _169) {
        var data = $.data(target, "datagrid").data;
        var view = $.data(target, "datagrid").options.view;
        var insertedRows = $.data(target, "datagrid").insertedRows;
        view.insertRow.call(view, target, _169.index, _169.row);
        insertedRows.push(_169.row);
        $(target).datagrid("getPager").pagination("refresh", {
            total: data.total
        });
    };

    function appendRow(target, row) {
        var data = $.data(target, "datagrid").data;
        var view = $.data(target, "datagrid").options.view;
        var insertedRows = $.data(target, "datagrid").insertedRows;
        view.insertRow.call(view, target, null, row);
        insertedRows.push(row);
        $(target).datagrid("getPager").pagination("refresh", {
            total: data.total
        });
    };

    function loadData(target) {
        var datagrid = $.data(target, "datagrid");
        var data = datagrid.data;
        var rows = data.rows;
        var originalRows = [];
        for (var i = 0; i < rows.length; i++) {
            originalRows.push($.extend({}, rows[i]));
        }
        datagrid.originalRows = originalRows;
        datagrid.updatedRows = [];
        datagrid.insertedRows = [];
        datagrid.deletedRows = [];
    };

    function acceptChanges(target) {
        var data = $.data(target, "datagrid").data;
        var ok = true;
        for (var i = 0, len = data.rows.length; i < len; i++) {
            if (validateRow(target, i)) {
                endEdit(target, i, false);
            } else {
                ok = false;
            }
        }
        if (ok) {
            loadData(target);
        }
    };

    function rejectChanges(target) {
        var datagrid = $.data(target, "datagrid");
        var opts = datagrid.options;
        var originalRows = datagrid.originalRows;
        var insertedRows = datagrid.insertedRows;
        var deletedRows = datagrid.deletedRows;
        var selectedRows = datagrid.selectedRows;
        var checkedRows = datagrid.checkedRows;
        var data = datagrid.data;

        function _pushIds(a) {
            var ids = [];
            for (var i = 0; i < a.length; i++) {
                ids.push(a[i][opts.idField]);
            }
            return ids;
        };

        function _findRowIndex(ids, _17e) {
            for (var i = 0; i < ids.length; i++) {
                var id = getRowIndex(target, ids[i]);
                if (id >= 0) {
                    (_17e == "s" ? selectRow : checkRow)(target, id, true);
                }
            }
        };
        for (var i = 0; i < data.rows.length; i++) {
            endEdit(target, i, true);
        }
        var selectedRowsIds = _pushIds(selectedRows);
        var checkedRowsIds = _pushIds(checkedRows);
        selectedRows.splice(0, selectedRows.length);
        checkedRows.splice(0, checkedRows.length);
        data.total += deletedRows.length - insertedRows.length;
        data.rows = originalRows;
        renderDatagridLoadData(target, data);
        _findRowIndex(selectedRowsIds, "s");
        _findRowIndex(checkedRowsIds, "c");
        loadData(target);
    };

    function request(target, param) {
        var opts = $.data(target, "datagrid").options;
        if (param) {
            opts.queryParams = param;
        }
        var optsQueryParams = opts.queryParams;
        if (typeof (opts.queryParams) == "function") {
            optsQueryParams = opts.queryParams();
        }
        var queryParams = {};
        if (optsQueryParams) {
            if (typeof (optsQueryParams) == "object") {
                queryParams = $.extend({}, optsQueryParams);
                queryParams.queryString = $.parser.objConvertStr(optsQueryParams);
                if (opts.pagination) {
                    $.extend(queryParams, {
                        page: opts.pageNumber,
                        rows: opts.pageSize
                    });
                }
                if (opts.sortName) {
                    $.extend(queryParams, {
                        sort: opts.sortName,
                        order: opts.sortOrder
                    });
                }
            } else {
                //如果，使用字符串作为参数的话，就无法使用分页功能，那么分页功能必须作为字符串的形式传入
                queryParams = optsQueryParams;
                if (opts.pagination) {
                    queryParams = queryParams + "&page=" + opts.pageNumber + "&rows=" + opts.pageSize;
                }
                if (opts.sortName) {
                    queryParams = queryParams + "&sort=" + opts.sortName + "&order=" + opts.sortOrder;
                }
            }
        } else {
            if (opts.pagination) {
                $.extend(queryParams, {
                    page: opts.pageNumber,
                    rows: opts.pageSize
                });
            }
            if (opts.sortName) {
                $.extend(queryParams, {
                    sort: opts.sortName,
                    order: opts.sortOrder
                });
            }
        }

        if (opts.onBeforeLoad.call(target, queryParams) == false) {
            return;
        }
        $(target).datagrid("loading");
        setTimeout(function () {
            _loaderData();
        }, 0);

        function _loaderData() {
            var _bool = opts.loader.call(target, queryParams, function (data) {
                setTimeout(function () {
                    $(target).datagrid("loaded");
                }, 0);
                renderDatagridLoadData(target, data);
                setTimeout(function () {
                    loadData(target);
                }, 0);
            }, function () {
                setTimeout(function () {
                    $(target).datagrid("loaded");
                }, 0);
                opts.onLoadError.apply(target, arguments);
            });
            if (_bool == false) {
                $(target).datagrid("loaded");
            }
        };
    };

    function mergeCells(target, cellObject) {
        var opts = $.data(target, "datagrid").options;
        cellObject.type = cellObject.type || "body";
        cellObject.rowspan = cellObject.rowspan || 1;
        cellObject.colspan = cellObject.colspan || 1;
        if (cellObject.rowspan == 1 && cellObject.colspan == 1) {
            return;
        }
        var tr = opts.finder.getTr(target, (cellObject.index != undefined ? cellObject.index : cellObject.id), cellObject.type);
        if (!tr.length) {
            return;
        }
        var td = tr.find("td[field=\"" + cellObject.field + "\"]");
        td.attr("rowspan", cellObject.rowspan).attr("colspan", cellObject.colspan);
        td.addClass("datagrid-td-merged");
        _tdHide(td.next(), cellObject.colspan - 1);
        for (var i = 1; i < cellObject.rowspan; i++) {
            tr = tr.next();
            if (!tr.length) {
                break;
            }
            td = tr.find("td[field=\"" + cellObject.field + "\"]");
            _tdHide(td, cellObject.colspan);
        }
        setMergedWidth(target);

        function _tdHide(td, _len) {
            for (var i = 0; i < _len; i++) {
                td.hide();
                td = td.next();
            }
        };
    };
    $.fn.datagrid = function (options, param) {
        if (typeof options == "string") {
            return $.fn.datagrid.methods[options](this, param);
        }
        options = options || {};
        return this.each(function () {
            var datagrid = $.data(this, "datagrid");
            var opts;
            if (datagrid) {
                opts = $.extend(datagrid.options, options);
                datagrid.options = opts;
            } else {
                opts = $.extend({}, $.extend({}, $.fn.datagrid.defaults, {
                    queryParams: {}
                }), $.fn.datagrid.parseOptions(this), options);
                $(this).css("width", "").css("height", "");
                var datagridObject = buildDatagrid(this, opts.rownumbers);
                if (!opts.columns) {
                    opts.columns = datagridObject.columns;
                }
                if (!opts.frozenColumns) {
                    opts.frozenColumns = datagridObject.frozenColumns;
                }
                opts.columns = $.extend(true, [], opts.columns);
                opts.frozenColumns = $.extend(true, [], opts.frozenColumns);
                opts.view = $.extend({}, opts.view);
                $.data(this, "datagrid", {
                    options: opts,
                    panel: datagridObject.panel,
                    dc: datagridObject.dc,
                    ss: null,
                    selectedRows: [],
                    checkedRows: [],
                    data: {
                        total: 0,
                        rows: []
                    },
                    originalRows: [],
                    updatedRows: [],
                    insertedRows: [],
                    deletedRows: []
                });
            }
            createDatagrid(this);
            bindEvent(this);
            resizeGrid(this);
            if (opts.data) {
                renderDatagridLoadData(this, opts.data);
                loadData(this);
            } else {
                var data = $.fn.datagrid.parseData(this);
                if (data.total > 0) {
                    renderDatagridLoadData(this, data);
                    loadData(this);
                }
            }
            if (opts.url) {
                request(this);
            }

        });
    };

    function _190(_191) {
        var _192 = {};
        $.map(_191, function (name) {
            _192[name] = _193(name);
        });
        return _192;

        function _193(name) {
            function isA(_194) {
                return $.data($(_194)[0], name) != undefined;
            };
            return {
                init: function (target, val) {
                    var parent = $("<input type=\"text\" class=\"datagrid-editable-input\">").appendTo(target);
                    if (parent[name] && name != "text") {
                        return parent[name](val);
                    } else {
                        return parent;
                    }
                },
                destroy: function (target) {
                    if (isA(target, name)) {
                        $(target)[name]("destroy");
                    }
                },
                getValue: function (target) {
                    if (isA(target, name)) {
                        var opts = $(target)[name]("options");
                        if (opts.multiple) {
                            return $(target)[name]("getValues").join(opts.separator);
                        } else {
                            return $(target)[name]("getValue");
                        }
                    } else {
                        return $(target).val();
                    }
                },
                setValue: function (target, val) {
                    if (isA(target, name)) {
                        var opts = $(target)[name]("options");
                        if (opts.multiple) {
                            if (val) {
                                $(target)[name]("setValues", val.split(opts.separator));
                            } else {
                                $(target)[name]("clear");
                            }
                        } else {
                            $(target)[name]("setValue", val);
                        }
                    } else {
                        $(target).val(val);
                    }
                },
                resize: function (target, width) {
                    if (isA(target, name)) {
                        $(target)[name]("resize", width);
                    } else {
                        $(target)._outerWidth(width)._outerHeight(22);
                    }
                }
            };
        };
    };
    var editorsTool = $.extend({}, _190(["text", "textbox", "numberbox", "numberspinner",
            "combobox", "combotree", "combogrid", "datebox",
            "datetimebox", "timespinner", "datetimespinner", "butcombo", "butcombogrid"]),
        {
            butcombo: {
                init: function (target, _1a0) {
                    var textarea = $("<a class=\"easyui-butcombo\">sadf</a>").appendTo(target);
                    textarea.butcombo(_1a0);
                    return target;
                },
                getValue: function (target) {
                    return $(target).val();
                },
                setValue: function (target, val) {
                    $(target).val(val);
                },
                resize: function (target, width) {
                    $(target)._outerWidth(width);
                }
            },
            butcombogrid: {
                init: function (target, _1a0) {
                    var textarea = $("<textarea class=\"datagrid-editable-input\"></textarea>").appendTo(target);
                    return textarea;
                },
                getValue: function (target) {
                    return $(target).val();
                },
                setValue: function (target, val) {
                    $(target).val(val);
                },
                resize: function (target, width) {
                    $(target)._outerWidth(width);
                }
            },
            textarea: {
                init: function (target, _1a0) {
                    var textarea = $("<textarea class=\"datagrid-editable-input\"></textarea>").appendTo(target);
                    return textarea;
                },
                getValue: function (target) {
                    return $(target).val();
                },
                setValue: function (target, val) {
                    $(target).val(val);
                },
                resize: function (target, width) {
                    $(target)._outerWidth(width);
                }
            },
            checkbox: {
                init: function (target, val) {
                    var checkbox = $("<input type=\"checkbox\">").appendTo(target);
                    checkbox.val(val.on);
                    checkbox.attr("offval", val.off);
                    return checkbox;
                },
                getValue: function (target) {
                    if ($(target).is(":checked")) {
                        return $(target).val();
                    } else {
                        return $(target).attr("offval");
                    }
                },
                setValue: function (target, val) {
                    var _bool = false;
                    if ($(target).val() == val) {
                        _bool = true;
                    }
                    $(target)._propAttr("checked", _bool);
                }
            },
            validatebox: {
                init: function (target, val) {
                    var box = $("<input type=\"text\" class=\"datagrid-editable-input\">").appendTo(target);
                    box.validatebox(val);
                    return box;
                },
                destroy: function (target) {
                    $(target).validatebox("destroy");
                },
                getValue: function (target) {
                    return $(target).val();
                },
                setValue: function (target, val) {
                    $(target).val(val);
                },
                resize: function (target, width) {
                    $(target)._outerWidth(width)._outerHeight(22);
                }
            }
        });
    $.fn.datagrid.methods = {
        options: function (jq) {
            var _opts = $.data(jq[0], "datagrid").options;
            var _pPpts = $.data(jq[0], "datagrid").panel.panel("options");
            var opts = $.extend(_opts, {
                width: _pPpts.width,
                height: _pPpts.height,
                closed: _pPpts.closed,
                collapsed: _pPpts.collapsed,
                minimized: _pPpts.minimized,
                maximized: _pPpts.maximized
            });
            return opts;
        },
        setSelectionState: function (jq) {
            return jq.each(function () {
                setSelectionState(this);
            });
        },
        createStyleSheet: function (jq) {
            return createStyleSheet(jq[0]);
        },
        getPanel: function (jq) {
            return $.data(jq[0], "datagrid").panel;
        },
        getPager: function (jq) {
            return $.data(jq[0], "datagrid").panel.children("div.datagrid-pager");
        },
        getColumnFields: function (jq, param) {
            return getColumnFields(jq[0], param);
        },
        getColumnOption: function (jq, param) {
            return getColumnOption(jq[0], param);
        },
        resize: function (jq, param) {
            return jq.each(function () {
                resizeGrid(this, param);
            });
        },
        load: function (jq, param) {
            return jq.each(function () {
                var opts = $(this).datagrid("options");
                if (typeof param == "string") {
                    opts.url = param;
                    param = null;
                }
                opts.pageNumber = 1;
                var pager = $(this).datagrid("getPager");
                pager.pagination("refresh", {pageNumber: 1});
                request(this, param);
            });
        },
        reload: function (jq, param) {
            return jq.each(function () {
                var opts = $(this).datagrid("options");
                if (typeof param == "string") {
                    opts.url = param;
                    param = null;
                }
                request(this, param);
            });
        },
        reloadFooter: function (jq, param) {
            return jq.each(function () {
                var opts = $.data(this, "datagrid").options;
                var dc = $.data(this, "datagrid").dc;
                if (param) {
                    $.data(this, "datagrid").footer = param;
                }
                if (opts.showFooter) {
                    opts.view.renderFooter.call(opts.view, this, dc.footer2, false);
                    opts.view.renderFooter.call(opts.view, this, dc.footer1, true);
                    if (opts.view.onAfterRender) {
                        opts.view.onAfterRender.call(opts.view, this);
                    }
                    $(this).datagrid("fixRowHeight");
                }
            });
        },
        loading: function (jq) {
            return jq.each(function () {
                var opts = $.data(this, "datagrid").options;
                $(this).datagrid("getPager").pagination("loading");
                if (opts.loadMsg) {
                    var panel = $(this).datagrid("getPanel");
                    if (!panel.children("div.datagrid-mask").length) {
                        $("<div class=\"datagrid-mask\" style=\"display:block\"></div>").appendTo(panel);
                        var msg = $("<div class=\"datagrid-mask-msg\" style=\"display:block;left:50%\"></div>").html(opts.loadMsg).appendTo(panel);
                        msg._outerHeight(40);
                        msg.css({
                            marginLeft: (-msg.outerWidth() / 2),
                            lineHeight: (msg.height() + "px")
                        });
                    }
                }
            });
        },
        loaded: function (jq) {
            return jq.each(function () {
                $(this).datagrid("getPager").pagination("loaded");
                var panel = $(this).datagrid("getPanel");
                panel.children("div.datagrid-mask-msg").remove();
                panel.children("div.datagrid-mask").remove();
            });
        },
        fitColumns: function (jq) {
            return jq.each(function () {
                fitColumns(this);
            });
        },
        fixColumnSize: function (jq, param) {
            return jq.each(function () {
                fixColumnSize(this, param);
            });
        },
        fixRowHeight: function (jq, param) {
            return jq.each(function () {
                fixRowHeight(this, param);
            });
        },
        freezeRow: function (jq, param) {
            return jq.each(function () {
                freezeRow(this, param);
            });
        },
        autoSizeColumn: function (jq, param) {
            return jq.each(function () {
                autoSizeColumn(this, param);
            });
        },
        loadData: function (jq, data) {
            return jq.each(function () {
                renderDatagridLoadData(this, data);
                loadData(this);
            });
        },
        getData: function (jq) {
            return $.data(jq[0], "datagrid").data;
        },
        getRows: function (jq) {
            return $.data(jq[0], "datagrid").data.rows;
        },
        getFooterRows: function (jq) {
            return $.data(jq[0], "datagrid").footer;
        },
        getRowIndex: function (jq, id) {
            return getRowIndex(jq[0], id);
        },
        getChecked: function (jq) {
            return getChecked(jq[0]);
        },
        getSelected: function (jq) {
            var rows = getSelectedRow(jq[0]);
            return rows.length > 0 ? rows[0] : null;
        },
        getSelections: function (jq) {
            return getSelectedRow(jq[0]);
        },
        clearSelections: function (jq) {
            return jq.each(function () {
                var datagrid = $.data(this, "datagrid");
                var selectedRows = datagrid.selectedRows;
                selectedRows.splice(0, selectedRows.length);
                unselectAll(this);
                if (datagrid.options.checkOnSelect) {
                    var checkedRows = datagrid.checkedRows;
                    checkedRows.splice(0, checkedRows.length);
                }
            });
        },
        clearChecked: function (jq) {
            return jq.each(function () {
                var datagrid = $.data(this, "datagrid");
                var selectedRows = datagrid.selectedRows;
                var checkedRows = datagrid.checkedRows;
                checkedRows.splice(0, checkedRows.length);
                uncheckAll(this);
                if (datagrid.options.selectOnCheck) {
                    selectedRows.splice(0, selectedRows.length);
                }
            });
        },
        scrollTo: function (jq, param) {
            return jq.each(function () {
                scrollTo(this, param);
            });
        },
        highlightRow: function (jq, param) {
            return jq.each(function () {
                highlightRow(this, param);
                scrollTo(this, param);
            });
        },
        selectAll: function (jq) {
            return jq.each(function () {
                selectAll(this);
            });
        },
        unselectAll: function (jq) {
            return jq.each(function () {
                unselectAll(this);
            });
        },
        selectRow: function (jq, param) {
            return jq.each(function () {
                selectRow(this, param);
            });
        },
        selectRecord: function (jq, id) {
            return jq.each(function () {
                var opts = $.data(this, "datagrid").options;
                if (opts.idField) {
                    var _id = getRowIndex(this, id);
                    if (_id >= 0) {
                        $(this).datagrid("selectRow", _id);
                    }
                }
            });
        },
        unselectRow: function (jq, param) {
            return jq.each(function () {
                unselectRow(this, param);
            });
        },
        checkRow: function (jq, param) {
            return jq.each(function () {
                checkRow(this, param);
            });
        },
        uncheckRow: function (jq, param) {
            return jq.each(function () {
                uncheckRow(this, param);
            });
        },
        checkAll: function (jq) {
            return jq.each(function () {
                checkAll(this);
            });
        },
        uncheckAll: function (jq) {
            return jq.each(function () {
                uncheckAll(this);
            });
        },
        beginEdit: function (jq, param) {
            return jq.each(function () {
                beginEdit(this, param);
            });
        },
        endEdit: function (jq, param) {
            return jq.each(function () {
                endEdit(this, param, false);
            });
        },
        cancelEdit: function (jq, param) {
            return jq.each(function () {
                endEdit(this, param, true);
            });
        },
        editCell: function (jq, param) {
            return jq.each(function () {
                editCell(this, param);
            });
        },
        getEditors: function (jq, param) {
            return getEditors(jq[0], param);
        },
        getEditor: function (jq, param) {
            return getEditor(jq[0], param);
        },
        refreshRow: function (jq, param) {
            return jq.each(function () {
                var opts = $.data(this, "datagrid").options;
                opts.view.refreshRow.call(opts.view, this, param);
            });
        },
        validateRow: function (jq, param) {
            return validateRow(jq[0], param);
        },
        updateRow: function (jq, param) {
            return jq.each(function () {
                var opts = $.data(this, "datagrid").options;
                opts.view.updateRow.call(opts.view, this, param.index, param.row);
            });
        },
        appendRow: function (jq, row) {
            return jq.each(function () {
                appendRow(this, row);
            });
        },
        insertRow: function (jq, param) {
            return jq.each(function () {
                insertRow(this, param);
            });
        },
        deleteRow: function (jq, param) {
            return jq.each(function () {
                deleteRow(this, param);
            });
        },
        getChanges: function (jq, param) {
            return getChanges(jq[0], param);
        },
        acceptChanges: function (jq) {
            return jq.each(function () {
                acceptChanges(this);
            });
        },
        rejectChanges: function (jq) {
            return jq.each(function () {
                rejectChanges(this);
            });
        },
        mergeCells: function (jq, param) {
            return jq.each(function () {
                mergeCells(this, param);
            });
        },
        showColumn: function (jq, param) {
            return jq.each(function () {
                var panel = $(this).datagrid("getPanel");
                panel.find("td[field=\"" + param + "\"]").show();
                $(this).datagrid("getColumnOption", param).hidden = false;
                $(this).datagrid("fitColumns");
            });
        },
        hideColumn: function (jq, param) {
            return jq.each(function () {
                var panel = $(this).datagrid("getPanel");
                panel.find("td[field=\"" + param + "\"]").hide();
                $(this).datagrid("getColumnOption", param).hidden = true;
                $(this).datagrid("fitColumns");
            });
        },
        sort: function (jq, param) {
            return jq.each(function () {
                sortGrid(this, param);
            });
        }
    };
    $.fn.datagrid.parseOptions = function (target) {
        var t = $(target);
        return $.extend({}, $.fn.panel.parseOptions(target), $.parser.parseOptions(target,
            ["url", "toolbar", "idField", "sortName", "sortOrder", "pagePosition", "resizeHandle",
                {
                    sharedStyleSheet: "boolean",
                    fitColumns: "boolean",
                    autoRowHeight: "boolean",
                    striped: "boolean",
                    nowrap: "boolean"
                }, {
                rownumbers: "boolean",
                singleSelect: "boolean",
                ctrlSelect: "boolean",
                checkOnSelect: "boolean",
                selectOnCheck: "boolean"
            }, {
                pagination: "boolean",
                pageSize: "number",
                pageNumber: "number"
            }, {
                multiSort: "boolean",
                remoteSort: "boolean",
                showHeader: "boolean",
                showFooter: "boolean"
            }, {
                scrollbarSize: "number"
            }]), {
            pageList: (t.attr("pageList") ? eval(t.attr("pageList")) : undefined),
            loadMsg: (t.attr("loadMsg") != undefined ? t.attr("loadMsg") : undefined),
            rowStyler: (t.attr("rowStyler") ? eval(t.attr("rowStyler")) : undefined)
        });
    };
    $.fn.datagrid.parseData = function (target) {
        var t = $(target);
        var data = {
            total: 0,
            rows: []
        };
        var columnFields = t.datagrid("getColumnFields", true).concat(t.datagrid("getColumnFields", false));
        t.find("tbody tr").each(function () {
            data.total++;
            var row = {};
            $.extend(row, $.parser.parseOptions(this, ["iconCls", "state"]));
            for (var i = 0; i < columnFields.length; i++) {
                row[columnFields[i]] = $(this).find("td:eq(" + i + ")").html();
            }
            data.rows.push(row);
        });
        return data;
    };
    var viewTool = {
        render: function (target, body, _bool) {
            var datagrid = $.data(target, "datagrid");
            var opts = datagrid.options;
            var rows = datagrid.data.rows;
            var _field = $(target).datagrid("getColumnFields", _bool);
            if (_bool) {
                if (!(opts.rownumbers || (opts.frozenColumns && opts.frozenColumns.length))) {
                    return;
                }
            }
            var btable = ["<table class=\"datagrid-btable\" cellspacing=\"0\" cellpadding=\"0\""];
            if (!_bool && rows.length <= 0 && opts.emptyMessage) {
                btable.push(" width=\"100%\" height=\"30\"");
            }
            btable.push(" border=\"0\"><tbody>");
            for (var i = 0; i < rows.length; i++) {
                var css = opts.rowStyler ? opts.rowStyler.call(target, i, rows[i]) : "";
                var className = "";
                var styleName = "";
                if (typeof css == "string") {
                    styleName = css;
                } else {
                    if (css) {
                        className = css["class"] || "";
                        styleName = css["style"] || "";
                    }
                }
                var cls = "class=\"datagrid-row " + (i % 2 && opts.striped ? "datagrid-row-alt " : " ") + className + "\"";
                var _styleCls = styleName ? "style=\"" + styleName + "\"" : "";
                var _rowIdStr = datagrid.rowIdPrefix + "-" + (_bool ? 1 : 2) + "-" + i;
                btable.push("<tr id=\"" + _rowIdStr + "\" datagrid-row-index=\"" + i + "\" " + cls + " " + _styleCls + ">");
                btable.push(this.renderRow.call(this, target, _field, _bool, i, rows[i]));
                btable.push("</tr>");
            }
            if (!_bool && rows.length <= 0 && opts.emptyMessage) {
                btable.push("<tr><td align='center'>您没有查询到数据</td></tr>");
            }
            btable.push("</tbody></table>");


            $(body).html(btable.join(""));
        },
        renderFooter: function (target, footer, _bool) {
            var opts = $.data(target, "datagrid").options;
            var rows = $.data(target, "datagrid").footer || [];
            var _field = $(target).datagrid("getColumnFields", _bool);
            var ftable = ["<table class=\"datagrid-ftable\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tbody>"];
            for (var i = 0; i < rows.length; i++) {
                ftable.push("<tr class=\"datagrid-row\" datagrid-row-index=\"" + i + "\">");
                ftable.push(this.renderRow.call(this, target, _field, _bool, i, rows[i]));
                ftable.push("</tr>");
            }
            ftable.push("</tbody></table>");
            $(footer).html(ftable.join(""));
        },
        renderRow: function (target, _fields, _bool, index, row) {
            var opts = $.data(target, "datagrid").options;
            var tdHtml = [];
            if (_bool && opts.rownumbers) {
                var rownumbers = index + 1;
                if (opts.pagination) {
                    rownumbers += (opts.pageNumber - 1) * opts.pageSize;
                }
                tdHtml.push("<td class=\"datagrid-td-rownumber\"><div class=\"datagrid-cell-rownumber\">" + rownumbers + "</div></td>");
            }
            for (var i = 0; i < _fields.length; i++) {
                var fieldIndex = _fields[i];
                var col = $(target).datagrid("getColumnOption", fieldIndex);
                if (col) {
                    var rowField = row[fieldIndex];
                    var css = col.styler ? (col.styler(rowField, row, index) || "") : "";
                    var className = "";
                    var styleName = "";
                    if (typeof css == "string") {
                        styleName = css;
                    } else {
                        if (css) {
                            className = css["class"] || "";
                            styleName = css["style"] || "";
                        }
                    }
                    var cls = className ? "class=\"" + className + "\"" : "";
                    var colHidden = col.hidden ? "style=\"display:none;" + styleName + "\"" : (styleName ? "style=\"" + styleName + "\"" : "");
                    tdHtml.push("<td field=\"" + fieldIndex + "\" " + cls + " " + colHidden + ">");
                    colHidden = "";
                    if (!col.checkbox) {
                        if (col.align) {
                            colHidden += "text-align:" + col.align + ";";
                        }
                        if (!opts.nowrap) {
                            colHidden += "white-space:normal;height:auto;";
                        } else {
                            if (opts.autoRowHeight) {
                                colHidden += "height:auto;";
                            }
                        }
                    }
                    tdHtml.push("<div style=\"" + colHidden + "\" ");
                    tdHtml.push(col.checkbox ? "class=\"datagrid-cell-check\"" : "class=\"datagrid-cell " + col.cellClass + "\"");
                    tdHtml.push(">");
                    if (col.checkbox) {
                        tdHtml.push("<input type=\"checkbox\" " + (row.checked ? "checked=\"checked\"" : ""));
                        tdHtml.push(" name=\"" + fieldIndex + "\" value=\"" + (rowField != undefined ? rowField : "") + "\">");
                    } else {
                        if (col.formatter) {
                            tdHtml.push(col.formatter(rowField, row, index, fieldIndex));
                        } else {
                            var dictionString = null;
                            try {
                                dictionString = dictionaryJson;
                            } catch (e) {
                            }
                            ;
                            if (col.dictionary && dictionString) {
                                try {
                                    rowField = dictionaryJson[col.dictionary][rowField];
                                } catch (e) {
                                }
                                ;
                            }
                            if (col.dateFormatt && rowField) {
                                try {
                                    var data = $.parser.parseDate(col.dateFormatt, rowField);
                                    rowField = $.parser.formatDate(col.dateFormatt, data);
                                } catch (e) {
                                }
                                ;
                            }
                            tdHtml.push(rowField || '');
                        }
                    }
                    tdHtml.push("</div>");
                    tdHtml.push("</td>");
                }
            }
            return tdHtml.join("");
        },
        refreshRow: function (target, index) {
            this.updateRow.call(this, target, index, {});
        },
        updateRow: function (target, id, row) {
            var opts = $.data(target, "datagrid").options;
            var rows = $(target).datagrid("getRows");
            $.extend(rows[id], row);
            var css = opts.rowStyler ? opts.rowStyler.call(target, id, rows[id]) : "";
            var className = "";
            var styleName = "";
            if (typeof css == "string") {
                styleName = css;
            } else {
                if (css) {
                    className = css["class"] || "";
                    styleName = css["style"] || "";
                }
            }
            className = "datagrid-row " + (id % 2 && opts.striped ? "datagrid-row-alt " : " ") + className;

            function selectRow(viewType) {
                var _field = $(target).datagrid("getColumnFields", viewType);
                var tr = opts.finder.getTr(target, id, "body", (viewType ? 1 : 2));
                var checked = tr.find("div.datagrid-cell-check input[type=checkbox]").is(":checked");
                tr.html(this.renderRow.call(this, target, _field, viewType, id, rows[id]));
                tr.attr("style", styleName).attr("class", tr.hasClass("datagrid-row-selected") ? className + " datagrid-row-selected" : className);
                if (checked) {
                    tr.find("div.datagrid-cell-check input[type=checkbox]")._propAttr("checked", true);
                }
            };
            selectRow.call(this, true);
            selectRow.call(this, false);
            $(target).datagrid("fixRowHeight", id);
        },
        insertRow: function (target, size, row) {
            var datagrid = $.data(target, "datagrid");
            var opts = datagrid.options;
            var dc = datagrid.dc;
            var data = datagrid.data;
            if (size == undefined || size == null) {
                size = data.rows.length;
            }
            if (size > data.rows.length) {
                size = data.rows.length;
            }

            function _insertRows(viewType) {
                var _view = viewType ? 1 : 2;
                for (var i = data.rows.length - 1; i >= size; i--) {
                    var tr = opts.finder.getTr(target, i, "body", _view);
                    tr.attr("datagrid-row-index", i + 1);
                    tr.attr("id", datagrid.rowIdPrefix + "-" + _view + "-" + (i + 1));
                    if (viewType && opts.rownumbers) {
                        var rownumbers = i + 2;
                        if (opts.pagination) {
                            rownumbers += (opts.pageNumber - 1) * opts.pageSize;
                        }
                        tr.find("div.datagrid-cell-rownumber").html(rownumbers);
                    }
                    if (opts.striped) {
                        tr.removeClass("datagrid-row-alt").addClass((i + 1) % 2 ? "datagrid-row-alt" : "");
                    }
                }
            };

            function _insertFields(viewType) {
                var _view = viewType ? 1 : 2;
                $(target).datagrid("getColumnFields", viewType);
                var idName = datagrid.rowIdPrefix + "-" + _view + "-" + size;
                var tr = "<tr id=\"" + idName + "\" class=\"datagrid-row\" datagrid-row-index=\"" + size + "\"></tr>";
                if (size >= data.rows.length) {
                    if (data.rows.length) {
                        opts.finder.getTr(target, "", "last", _view).after(tr);
                    } else {
                        var cc = viewType ? dc.body1 : dc.body2;
                        cc.html("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tbody>" + tr + "</tbody></table>");
                    }
                } else {
                    opts.finder.getTr(target, size + 1, "body", _view).before(tr);
                }
            };
            _insertRows.call(this, true);
            _insertRows.call(this, false);
            _insertFields.call(this, true);
            _insertFields.call(this, false);
            data.total += 1;
            data.rows.splice(size, 0, row);
            //显示表头
            if (data.total <= 0 && opts.emptyMessage) {
                dc.view1.children("div.datagrid-header").hide();
                dc.view2.children("div.datagrid-header").hide();
            } else {
                dc.view1.children("div.datagrid-header").show();
                dc.view2.children("div.datagrid-header").show();
            }
            this.refreshRow.call(this, target, size);
        },
        onBeforeRender: function (target, rows) {
        },
        onAfterRender: function (target) {
            var opts = $.data(target, "datagrid").options;
            if (opts.showFooter) {
                var footer = $(target).datagrid("getPanel").find("div.datagrid-footer");
                footer.find("div.datagrid-cell-rownumber,div.datagrid-cell-check").css("visibility", "hidden");
            }
        }
    };
    $.fn.datagrid.defaults = $.extend({}, $.fn.panel.defaults, {
        sharedStyleSheet: false,
        frozenColumns: undefined,
        columns: undefined,
        fitColumns: false,
        resizeHandle: "right",
        autoRowHeight: true,
        toolbar: null,
        striped: false,
        method: "post",
        nowrap: true,
        idField: null,
        url: null,
        data: null,
        loadMsg: "处理中, 请稍等 ...",
        rownumbers: false,
        singleSelect: false,
        ctrlSelect: false,
        selectOnCheck: true,
        checkOnSelect: true,
        pagination: false,
        showPageList: true,
        showMsg: true,
        showPageStyle: "links",
        pagePosition: "bottom",
        buttonPosition: "after",
        pageButtons: null,
        pageNumber: 1,
        pageSize: 10,
        pageList: [10, 20, 30, 40, 50],
        queryParams: {},
        sortName: null,
        sortOrder: "asc",
        multiSort: false,
        emptyMessage: false,
        remoteSort: true,
        showHeader: true,
        showFooter: false,
        scrollbarSize: 18,
        showEditor: false,
        finder: {
            getTr: function (target, id, type, body) {
                type = type || "body";
                body = body || 0;
                var grid = $.data(target, "datagrid");
                var dc = grid.dc;
                var opts = grid.options;
                if (body == 0) {
                    var tr1 = opts.finder.getTr(target, id, type, 1);
                    var tr2 = opts.finder.getTr(target, id, type, 2);
                    return tr1.add(tr2);
                } else {
                    if (type == "body") {
                        var tr = $("#" + grid.rowIdPrefix + "-" + body + "-" + id);
                        if (!tr.length) {
                            tr = (body == 1 ? dc.body1 : dc.body2).find(">table>tbody>tr[datagrid-row-index=" + id + "]");
                        }
                        return tr;
                    } else {
                        if (type == "footer") {
                            return (body == 1 ? dc.footer1 : dc.footer2).find(">table>tbody>tr[datagrid-row-index=" + id + "]");
                        } else {
                            if (type == "selected") {
                                return (body == 1 ? dc.body1 : dc.body2).find(">table>tbody>tr.datagrid-row-selected");
                            } else {
                                if (type == "highlight") {
                                    return (body == 1 ? dc.body1 : dc.body2).find(">table>tbody>tr.datagrid-row-over");
                                } else {
                                    if (type == "checked") {
                                        return (body == 1 ? dc.body1 : dc.body2).find(">table>tbody>tr.datagrid-row-checked");
                                    } else {
                                        if (type == "last") {
                                            return (body == 1 ? dc.body1 : dc.body2).find(">table>tbody>tr[datagrid-row-index]:last");
                                        } else {
                                            if (type == "allbody") {
                                                return (body == 1 ? dc.body1 : dc.body2).find(">table>tbody>tr[datagrid-row-index]");
                                            } else {
                                                if (type == "allfooter") {
                                                    return (body == 1 ? dc.footer1 : dc.footer2).find(">table>tbody>tr[datagrid-row-index]");
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            },
            getRow: function (target, p) {
                var index = (typeof p == "object") ? p.attr("datagrid-row-index") : p;
                return $.data(target, "datagrid").data.rows[parseInt(index)];
            },
            getRows: function (target) {
                return $(target).datagrid("getRows");
            }
        },
        rowStyler: function (target, param) {
        },
        loader: function (param, successCall, errorCall) {
            var opts = $(this).datagrid("options");
            if (!opts.url) {
                return false;
            }
            $.ajax({
                type: opts.method,
                url: opts.url,
                data: param,
                dataType: "json",
                success: function (data) {
                    if (jQuery.isArray(data)) {
                        successCall(data);
                    } else if (data.status) {
                        successCall(data.content);
                    } else {
                        $.messager.show({
                            title: "消息提示",
                            msg: data.message || "加载数据异常",
                            showType: "slide",
                            style: {
                                right: '',
                                top: document.body.scrollTop + document.documentElement.scrollTop,
                                bottom: ''
                            }
                        }, "error");
                        errorCall.apply(this, arguments);
                    }
                },
                error: function () {
                    errorCall.apply(this, arguments);
                }
            });
        },
        loadFilter: function (data) {
            if (typeof data.length == "number" && typeof data.splice == "function") {
                return {
                    total: data.length,
                    rows: data
                };
            } else {
                return data;
            }
        },
        editors: editorsTool,
        view: viewTool,
        onBeforeLoad: function (_24b) {
        },
        onLoadSuccess: function () {
        },
        onLoadError: function () {
        },
        onClickRow: function (_24c, _24d) {
        },
        onDblClickRow: function (_24e, _24f) {
        },
        onClickCell: function (_250, _251, _252) {
        },
        onDblClickCell: function (_253, _254, _255) {
        },
        onBeforeSortColumn: function (sort, _256) {
        },
        onSortColumn: function (sort, _257) {
        },
        onResizeColumn: function (_258, _259) {
        },
        onSelect: function (_25a, _25b) {
        },
        onUnselect: function (_25c, _25d) {
        },
        onSelectAll: function (rows) {
        },
        onUnselectAll: function (rows) {
        },
        onCheck: function (_25e, _25f) {
        },
        onUncheck: function (_260, _261) {
        },
        onCheckAll: function (rows) {
        },
        onUncheckAll: function (rows) {
        },
        onBeforeEdit: function (_262, _263) {
        },
        onBeginEdit: function (_264, _265) {
        },
        onEndEdit: function (_266, _267, _268) {
        },
        onAfterEdit: function (_269, _26a, _26b) {
        },
        onCancelEdit: function (_26c, _26d) {
        },
        onHeaderContextMenu: function (e, _26e) {
        },
        onRowContextMenu: function (e, _26f, _270) {
        }
    });
})(jQuery);